package shujuku.星期三180523课堂实践;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class 查询Max平均寿命 {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/world?" +
                "useUnicode=true&characterEncoding=UTF8&&user=root&&password=";
        Connection conn = (Connection) DriverManager.getConnection(url);
        Statement stmt = (Statement) conn.createStatement();
        try {
            String sql2 = "SELECT * FROM country WHERE country.LifeExpectancy=(SELECT MAX(country.LifeExpectancy)FROM country) ";
            ResultSet rs2 = stmt.executeQuery(sql2);
            while (rs2.next()) {
                System.out.println(rs2.getString("Code")+ "\t" +rs2.getString("Name")+"\t" +
                        rs2.getString("LifeExpectancy"));
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        finally{
            //7.关闭连接(顺序:后打开的先关闭)
            if(stmt!=null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
